const db = uniCloud.database();
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
	const uniIDIns = uniID.createInstance({ context });
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
	console.log(await uniIDIns.checkToken(body.uniIdToken))
	const { uid } = await uniIDIns.checkToken(body.uniIdToken);
	if (!uid) {
	    return { code: 403, message: "身份验证失败" };
	}
  
  try {
    const res = await db.collection("uni-id-users").where({
      _id: uid
    }).get();
	console.log(res)
    if (res.data.length > 0) {
	  const user = res.data[0];
	  return {
		code: 0,
		data: {
		  avatar_file: user.avatar_file || "/static/logo.png",
		  nickname: user.nickname || "未填写名称",
		  gender: user.gender || '未设置',
		  age: user.age || -1,
		  riskLevel: user.risk_level || '未知',
		  remainingCancelCount: user.remainingCancelCount || -1, // 默认为3次
		  uid
		}
	  };
    } else {
      return {
        code: 1,
        message: "未找到用户信息",
        data: {
          avatar_file: "/static/logo.png",
          nickname: "未填写名称",
		  gender:"未知",
		  age:-1,
		  riskLevel:"无风险等级",
		  remainingCancelCount:-1,
		  uid
        }
      };
    }
  } catch (error) {
    console.error("Database query failed:", error);
    return {
      code: -6,
      message: "数据库查询失败",
      data: {
        avatar_file: "/static/logo.png",
        nickname: "未填写名称",
		gender:"未知",
		age:-1,
		riskLevel:"无风险等级",
		remainingCancelCount:-1,
		uid
      }
    };
  }
};